<template>
  <div class="login-container">
    <div class="login-form">
      <el-form ref="loginRef" :model="loginUserInfo" :rules="loginRules">
        <el-form-item prop="username">
          <el-input
            v-model="loginUserInfo.username"
            prefix-icon="el-icon-user"
            @keyup.enter.native="userLogin"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginUserInfo.password"
            prefix-icon="el-icon-unlock"
            @keyup.enter.native="userLogin"
          ></el-input>
        </el-form-item>
        <div class="tips">账号：admin 密码：123456</div>
        <el-button type="default" @click="reset">重置</el-button>
        <el-button type="primary" @click="userLogin"> 登录 </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { setStorage } from '../utils/auth'
export default {
  name: 'login',
  data() {
    return {
      // 登录用户对象
      loginUserInfo: {
        username: '',
        password: '',
      },
      // 验证规则
      loginRules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    }
  },
  methods: {
    // 用户登录
    userLogin() {
      const { loginUserInfo } = this
      // 表单验证
      this.$refs.loginRef.validate(async v => {
        if (!v) return
        try {
          const userInfoData = await this.$store.dispatch(
            'user/userLogin',
            loginUserInfo
          )
          // 登录成功跳转首页，并将用户信息存储到本地
          this.$message.success('登录成功')
          // 先存储用户信息到本地，再路由跳转，否则第一次不会跳到首页
          setStorage('userInfo', userInfoData)
          this.$router.push('/home/visual')
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 点击重置的回调
    reset() {
      this.$refs.loginRef.resetFields()
    },
  },
}
</script>

<style lang="scss">
.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: $bg-color-gray;
  .login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 460px;
    height: 260px;
    background-color: #fff;
    border-radius: 10px;
    .el-form {
      width: 360px;
      margin: 40px auto 0;
      text-align: center;
      .tips {
        color: #ccc;
        font-size: 14px;
        margin-bottom: 15px;
      }
      .el-button {
        margin: 0 20px;
      }
    }
  }
}
</style>
